import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/home.vue';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: {
        tabbar: true,
        title: '首页',
      },
    },
    {
      path: '/cart',
      name: 'cart',
      component: () => import('../views/cart.vue'),
      meta: {
        auth: true,
        tabbar: true,
        title: '购物车',
      },
    },
    {
      path: '/address',
      name: 'address',
      component: () => import('../views/address/index.vue'),
      meta: {
        auth: true,
        tabbar: true,
        title: '地址管理',
      },
    },
    {
      path: '/address/add',
      name: 'add',
      component: () => import('../views/address/add.vue'),
      meta: {
        auth: true,
        title: '添加地址',
      },
    },
    {
      path: '/address/edit',
      name: 'edit',
      component: () => import('../views/address/edit.vue'),
      meta: {
        auth: true,
        title: '修改地址',
      },
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login.vue'),
      meta: {
        title: '登录',
      },
    },
  ],
});

router.beforeEach((to, from) => {
  if (to.meta.auth && !localStorage.getItem('token')) {
    return {
      name: 'login',
      query: { redirect: to.fullPath },
    };
  }
});

export default router;
